import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../http/api.dart';


class RetrieveAddress extends StatefulWidget {
  const RetrieveAddress({super.key, required this.addressType, required this.region});
  final int addressType;
  final String region;
  @override
  State<RetrieveAddress> createState() => _RetrieveAddressState();
}

class _RetrieveAddressState extends State<RetrieveAddress> {
  Map detailMap={};
  String detailAddress="";
  List<String> hisAddressLsit=[];
  List searchAddressList=[];
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        leading: IconButton(icon: Icon(Icons.arrow_back_ios,color: Colors.black,),onPressed: (){Navigator.pop(context);},),
        centerTitle: true,
        backgroundColor: Colors.white,

        title: Text(widget.addressType==1?"装货地址":"卸货地址",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ),
      body:Column(
        children: [
          Expanded(child: ListView(children: [
            Container(
              color: Colors.white,
              padding: EdgeInsets.only(top: 10.h,bottom: 10.h,left: 20.w,right: 20.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("详细地址",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                  checkDetialAddressSheet(region: widget.region,),
                  // SizedBox(height: 8.h,),
                  // Row(
                  //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  //   children: [
                  //     GestureDetector(s
                  //       child:   Container(
                  //         width:screenSize.width-40.w,
                  //         height: 30.h,
                  //         decoration: BoxDecoration(
                  //             color: MyColors.backgreyColor,
                  //             borderRadius: BorderRadius.all(Radius.circular(10))),
                  //         child:Center(
                  //           child:   detailAddress==""?
                  //           Text(widget.addressType==1?"必填，请输入装货详细地址":"必填，请输入卸货详细地址",style: TextStyle(color: MyColors.hintColor,fontSize: 14.sp),)
                  //               :Text(detailAddress,overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                  //         ),
                  //       ),
                  //       onTap: ()async{
                  //         final result=await showModalBottomSheet(context: context, builder: (BuildContext context) {
                  //           return checkDetialAddressSheet(region: widget.region,
                  //           );});
                  //         if (result !=null){
                  //           setState(() {
                  //             detailMap=result;
                  //             detailAddress=detailMap['address'];
                  //           });
                  //         }
                  //       },
                  //     ),
                  //
                  //   ],
                  // ),
                ],
              ),
            ),
          ],),

          ),

        ],
      )
    );
  }
}
class checkDetialAddressSheet extends StatefulWidget {
  const checkDetialAddressSheet({super.key, required this.region});
  final String region;
  @override
  State<checkDetialAddressSheet> createState() => _checkDetialAddressSheetState();
}

class _checkDetialAddressSheetState extends State<checkDetialAddressSheet> {
  List dataList=[];
  Future<void> searchAddressAction(String query) async {
    String? token =await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.get<String>(MyServiceUrl.header+ "api/system/dev/cityDict/detailList?query=$query&region=${widget.region}")
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          dataList=jsonMap['data'];
          dataList = dataList.where((dict) {
            return dict['address'] != null && dict['address'].toString().isNotEmpty;
          }).toList();
          print(dataList);
        } else {
          BrnToast.show(jsonMap['msg'], context);
        }



      });
    }).catchError((error) {
      print(error);
    });
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Container(
      padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 15.h),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      child: Column(
        children: [

          Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(10))),
            width:screenSize.width-20.w,
            height: 40.h,
            child:  TextField(
              decoration: InputDecoration(
                hintText: '请输入详细地址',
                hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                filled: true,
                fillColor: MyColors.backgreyColor,
                border: InputBorder.none,
                alignLabelWithHint: true,
                contentPadding: EdgeInsets.symmetric(vertical: 8.0.h, horizontal: 6.0.w),
              ),
              textAlign: TextAlign.left,
              style: TextStyle(color: Colors.black),
              onChanged: (value) {
                setState(() {
                  searchAddressAction(value);
                });
              },
            ),
          ),
          SizedBox(height: 10.h,),
          Container(
            width: screenSize.width-20.w,
            height: screenSize.height-200.h,
            color: Colors.white,
            child:  ListView.builder(
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                itemCount: dataList.length,
                itemBuilder: (BuildContext context,
                    int index) {
                  return GestureDetector(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(dataList[index]['address'],style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                        Divider(height: 16.h,color: MyColors.backgreyColor,),
                      ],
                    ),
                    onTap: (){
                      print(dataList[index]);
                      Navigator.pop(context,dataList[index]);
                    },
                  );
                }
            ),
          )
        ],
      ),
    );
  }
}
